package org.ls.petclinic.web;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import org.ls.petclinic.dao.CustomerDao;
import org.ls.petclinic.dao.impl.CustomerDaoImpl;
import org.ls.petclinic.pojo.Customer;
import org.ls.petclinic.untils.JdbcUtils;
import org.ls.petclinic.untils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description
 * @Author 浪矢先生
 * @Create 2022-06-10 0:50
 */
@WebServlet(urlPatterns = "/getCustomer")
public class GetCustomerServlet extends BaseServlet{
    private CustomerDao customerDao=new CustomerDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Gson gson = new Gson();
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        String id = req.getParameter("id");
        if (StrUtil.hasBlank(id)){
            List<Customer> customerList = customerDao.getCustomer();
            JdbcUtils.commitAndClose();
            resp.getWriter().write(String.valueOf(gson.toJson(customerList)));
        }else {
            Customer customer = customerDao.getCustomerById(WebUtils.parseInt(id, 0));
            JdbcUtils.commitAndClose();
            resp.getWriter().write(String.valueOf(gson.toJson(customer)));
        }
    }
}
